package cn.spring.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.spring.bean.Commodity;
import cn.spring.bean.Employee;
import cn.spring.service.AddressService;
import cn.spring.service.CommodityService;
import cn.spring.service.EmplyoeeService;


@Controller
@RequestMapping("/emp")
public class UserController {
	
	@Autowired
	private EmplyoeeService biz;
	
	@Autowired
	private CommodityService cBiz;
	
	@Autowired
	private AddressService aBiz;
	
	@RequestMapping("/getIndex")
	public String getIndex(Model model,HttpServletRequest request,HttpServletResponse response){
		Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
		String path =request.getSession().getServletContext().getRealPath("/");  
		System.out.println(path);
		Employee user=new Employee();
        if (null==cookies) {
        	return "../login";
        } else {
        	Boolean pan=false;
            for(Cookie cookie : cookies){
           	 if(cookie.getName().equals("phone")){
           		user.setAccount(cookie.getValue());
           		pan=true;
           	 }
           	 if(cookie.getName().equals("pwd")){
           		user.setPwd(cookie.getValue());
           		pan=true;
           	 }
            }
            if(pan){
            	user=biz.login(user);
            	if(user.getIsTong()==0){
    				model.addAttribute("msg", "账号审核未通过！");
    				return "../login";
    			}
            	model.addAttribute("login", user);
    			request.getSession().setAttribute("emp", user);
    			model.addAttribute("msg", "");
    			int count=aBiz.addressCount(user.getId());
    			if(count>0){
    				List<Map<String, Object>> piList=new ArrayList<Map<String, Object>>();
    				List<Map<String, Object>> xianList=new ArrayList<Map<String, Object>>();
    				List<Map<String, Object>> yinList=new ArrayList<Map<String, Object>>();
    				List<Map<String, Object>> list=cBiz.findAll(user.getId());
    				int zong=0;
    				for(Map<String, Object> co:list){
    					int typeId=Integer.parseInt(co.get("typeId").toString());
    					if(typeId==1){
    						piList.add(co);
    					}else if(typeId==2){
    						xianList.add(co);
    					}else{
    						yinList.add(co);
    					}
    					int num=Integer.parseInt(co.get("num").toString());
    					zong+=num;
    				}
    				model.addAttribute("piList", piList);
    				model.addAttribute("xianList", xianList);
    				model.addAttribute("yinList", yinList);
    				model.addAttribute("zong", zong);
    				return "../index";
	            }else{
	            	return "../addAddress";
	            }
            }else{
            	return "../login";
            }
        }
	}
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@ModelAttribute Employee emp,Model model,HttpServletRequest request,HttpServletResponse response) {
		 Employee user=biz.login(emp);
		
		if(user!=null){
			if(user.getIsTong()==0){
				model.addAttribute("msg", "账号审核未通过！");
				return "../login";
			}
			model.addAttribute("login", user);
			request.getSession().setAttribute("emp", user);
			Cookie cookie = new Cookie("phone",emp.getAccount());
			response.addCookie(cookie);
			cookie = new Cookie("pwd",emp.getPwd());
			response.addCookie(cookie);
			model.addAttribute("msg", "");
			int count=aBiz.addressCount(user.getId());
			if(count>0){
				List<Map<String, Object>> piList=new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> xianList=new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> yinList=new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> list=cBiz.findAll(user.getId());
				int zong=0;
				for(Map<String, Object> co:list){
					int typeId=Integer.parseInt(co.get("typeId").toString());
					if(typeId==1){
						piList.add(co);
					}else if(typeId==2){
						xianList.add(co);
					}else{
						yinList.add(co);
					}
					int num=Integer.parseInt(co.get("num").toString());
					zong+=num;
				}
				model.addAttribute("piList", piList);
				model.addAttribute("xianList", xianList);
				model.addAttribute("yinList", yinList);
				model.addAttribute("zong", zong);
				return "../index";
			}else{
				return "../addAddress";
			}
		}else{
			model.addAttribute("msg", "账号或密码错误！");
			return "../login";
		}
	}
	
	@RequestMapping("/registered")
	public String registered(@ModelAttribute Employee emp,Model model,HttpServletRequest request,HttpServletResponse response){
		if(emp.getAccount()!=null&&emp.getPwd()!=null&&emp.getName()!=null&&emp.getAccount().length()==11) {
		emp.setRole(2);
		emp.setIsTong(0);
		int count=biz.phonePan(emp.getAccount());
		if(count>0){
			request.getSession().setAttribute("msg", "您的手机已存在，请登录！");
			return "../register";
		}else {
			Employee user=biz.save(emp);
			if(user!=null){
				model.addAttribute("login", user);
				request.getSession().setAttribute("emp", user);
				/*List<Map<String, Object>> piList=new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> xianList=new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> yinList=new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> list=cBiz.findAll();
				for(Map<String, Object> co:list){
					if(co.get("typeId").equals("1")){
						piList.add(co);
					}else if(co.get("typeId").equals("2")){
						xianList.add(co);
					}else{
						yinList.add(co);
					}
				}
				model.addAttribute("piList", piList);
				model.addAttribute("xianList", xianList);
				model.addAttribute("yinList", yinList);
				model.addAttribute("zong", 0);*/
				return "../login";
				
			}else{
				model.addAttribute("msg", "注册失败！");
				return "../register";
			}
		}
		}else {
			return "../login";
		}
		
	}
	
	/**
	 * 判断手机号是否存在
	 */
	@RequestMapping("/phonePan")
	@ResponseBody
	public String phonePan(@RequestParam("account")String account){
		int count=biz.phonePan(account);
		if(count>0){
			return "您的手机已存在，请登录！";
		}else{
			return "1";
		}
	}
	
	@RequestMapping("/goMember")
	public String goMember(Model model,HttpServletRequest request){
		model.addAttribute("login", (Employee)request.getSession().getAttribute("emp"));
		return "../member";
	}
	
	@RequestMapping("/adminLogin")
	public String adminLogin(Model model,HttpServletRequest request,HttpServletResponse response,@ModelAttribute Employee emp,@RequestParam(value="ji",defaultValue="")String ji,HttpSession session){
		Employee user=biz.login(emp);
		if(user!=null){
			if(user.getIsTong()==0){
				model.addAttribute("msg", "账号审核未通过！");
				return "../admin/login";
			}
			if(user.getRole()==1){
				List<Employee> list=biz.findAll();
				model.addAttribute("list", list);
				request.getSession().setAttribute("emp", user);
				session.setAttribute("acc", user.getAccount());
				session.setAttribute("pwd", user.getPwd());
				model.addAttribute("msg", "");
				if(ji.length()>0){
					Cookie cookie = new Cookie("adminPhone",emp.getAccount());
					response.addCookie(cookie);
					cookie = new Cookie("adminPwd",emp.getPwd());
					response.addCookie(cookie);
				}
				return "../admin/tables";
			}else{
				model.addAttribute("msg", "您不是管理员！");
				return "../admin/login";
			}
		}else{
			model.addAttribute("msg", "账号或密码错误！");
			return "../admin/login";
		}
	}
	
	@RequestMapping("/getAdmin")
	public String getAdmin(Model model,HttpServletRequest request,HttpServletResponse response){
		Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
		Employee user=new Employee();
        if (null==cookies) {
        	return "../admin/login";
        } else {
        	Boolean pan=false;
            for(Cookie cookie : cookies){
           	 if(cookie.getName().equals("adminPhone")){
           		user.setAccount(cookie.getValue());
           		pan=true;
           	 }
           	 if(cookie.getName().equals("adminPwd")){
           		user.setPwd(cookie.getValue());
           		pan=true;
           	 }
            }
            if(pan){
            	user=biz.login(user);
            	List<Employee> list=biz.findAll();
				model.addAttribute("list", list);
    			request.getSession().setAttribute("emp", user);
    			model.addAttribute("msg", "");
    			return "../admin/tables";
            }else{
            	model.addAttribute("msg", "");
    			return "../admin/login";
            }
        }
	}
	
	@RequestMapping("/editState")
	public String editState(@RequestParam("id")Integer id,@RequestParam("state")Integer state,Model model){
		int count=biz.updateIstong(id, state);
		if(count>0){
			List<Employee> list=biz.findAll();
			model.addAttribute("list", list);
			return "../admin/tables";
		}else{
			model.addAttribute("msg", "更新失败，请重新操作或检查数据");
			return "../admin/error";
		}
	}
	
	@RequestMapping("/getAll")
	public String getAll(Model model){
		List<Employee> list=biz.findAll();
		model.addAttribute("list", list);
		return "../admin/tables";
	}
	
	@RequestMapping("/deleteEmp")
	public String deleteEmp(@RequestParam("id")Integer id,@RequestParam("role")Integer role,Model model){
		int count=biz.updateIstong(id, role);
		
		if(count>0){
			List<Employee> list=biz.findAll();
			model.addAttribute("list", list);
			return "../admin/tables";
		}else{
			model.addAttribute("msg", "删除失败，请重新操作或检查数据");
			return "../admin/error";
		}
	}
	@RequestMapping("/layout")
	public String layout(HttpSession session) {
		session.invalidate();
		return "../login";
	}
	
	@RequestMapping("/xiugai")
	public String xiugai(Model model,Integer id) {
		List<Employee> elist=biz.findAllById(id);
		model.addAttribute("elist", elist);
		return "../admin/xiugai";
	}
	@RequestMapping("/xiugaidianming")
	public String xiugaidianming(Model model,HttpServletRequest request,HttpServletResponse response,String name,@Param("id")Integer id) throws UnsupportedEncodingException {
		String name1 = java.net.URLDecoder.decode(name,"UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		//System.out.println(name1);
		biz.xiugaidianming(name1, id);
		List<Employee> list=biz.findAll();
		model.addAttribute("list", list);
		return "../admin/tables";
	}
	
	@RequestMapping("/updatePwd")
	public String updatePwd(@RequestParam("pwd")String pwd,HttpServletRequest request) {
		Employee emp=(Employee)request.getSession().getAttribute("emp");
		int count=biz.updatePwd(pwd, emp.getId());
		if(count>0) {
			return "../admin/login";
		}else {
			return "../admin/error";
		}
	}
}

	
